const express = require('express');
const router = express.Router();
const { Op } = require('sequelize');
const { Course } = require('../models');
const { success, failure } = require('../utils/responses');
const { NotFound, BadRequest } = require('http-errors');
const {chaptersIndex, coursesIndex} = require('../utils/meilisearch')

/**
 * 查询课程列表
 *
 * GET /search?q=node&type=courses
 * GET /search?q=node&type=chapters
 * */

router.get('/', async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    const { q, type} = query;
    const option = {
      attributesToHighlight: ['*'],
      offset,
      limit: pageSize
    }
    let results;
    switch(type) {
      case 'courses':
        results = await coursesIndex.search(q, option);
        break;
      case 'chapters':
        results = await chaptersIndex.search(q, option);
        break;
      default:
        throw new BadRequest('搜错类型错误')
    }
    const data = {}
    data[type] = results.hits;

    // const condition = {
    //   where: {},
    //   attributes: { exclude: ['content', 'CategoryId', 'UserId'] },
    //   order: [['id', 'desc']],
    //   limit: pageSize,
    //   offset,
    // };
    // if (query.name) {
    //   condition.where.name = {
    //     [Op.like]: `%${query.name}%`,
    //   };
    // }
    // const { count, rows } = await Course.findAndCountAll(condition);

    success(res, '查询成功', {
      // articles: rows,
      ...data,
      pagination: {
        total: results.estimatedTotalHits,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
